package ren.kane.phoenix.util.schedule;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ren.kane.phoenix.util.common.RestResult;
import ren.kane.phoenix.util.common.ResultEnum;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * @author renrk(1275) on 2019-04-11 3:17 PM
 **/
@CrossOrigin
@RestController
@RequestMapping("/phoenix/schedule")
public class ScheduleController {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> scheduledFuture;

    private String cron = "0/20 * * * * ?";

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @GetMapping("/cron")
    @ApiOperation(value = "查询cron表达式", httpMethod = "GET")
    public RestResult getCron() {
        return RestResult.success(cron);
    }

    @GetMapping("/stop")
    @ApiOperation(value = "停止定时任务", httpMethod = "GET")
    public RestResult stopCron() {
        System.out.println("try to stop");
        if (null != scheduledFuture) {
            scheduledFuture.cancel(true);
        }
        return RestResult.success();
    }

    @GetMapping("/start")
    @ApiOperation(value = "启动定时任务", httpMethod = "GET")
    public RestResult startCron() {
        if (StringUtils.isBlank(cron)) {
            System.out.println("cron is null");
            return RestResult.error(ResultEnum.PARAM_NULL_ERROR);
        }
        if (!CronExpression.isValidExpression(cron)) {
            System.out.println("cron format is error");
            return RestResult.error(ResultEnum.PARAM_FORMAT_ERROR);
        }
        stopCron();
        System.out.println("try to start");
        scheduledFuture = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger(cron));
        return RestResult.success("cron: " + cron);
    }

    @PostMapping("/reset")
    @ApiOperation(value = "重启定时任务", httpMethod = "POST")
    public RestResult resetCron(@RequestParam String cron) {
        this.cron = cron;
        startCron();
        return RestResult.success("cron: " + cron);
    }

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("ready to run schedule task, " + new Date());
        }
    }
}

